package com.liuqi.loggers.core.appender;

import com.liuqi.loggers.core.LoggerEvent;
import com.liuqi.loggers.core.LoggingException;
import com.liuqi.loggers.core.rolling.RollingPolicy;
import com.liuqi.loggers.core.rolling.RolloverFailure;
import java.io.IOException;

/**
 * 日志文件滚动输出, 滚动策略{@link #rollingPolicy} 备份文件
 *
 * @author liuqi
 * @date 2024/6/6 13:45
 **/
public class RollingFileAppender extends FileAppender {

    /**
     * 日志文件滚动策略
     */
    private RollingPolicy rollingPolicy;

    @Override
    public void append(LoggerEvent event) throws LoggingException {
        lock.lock();
        try {
            if (rollingPolicy != null) {
                if (rollingPolicy.isTriggering(event)) {
                    // 滚动日志文件
                    rollover();
                }
            }
        } finally {
            lock.unlock();
        }
        super.append(event);
    }

    @Override
    public void start() {
        if (rollingPolicy == null) {
            throw new NullPointerException("rollingPolicy cannot be null");
        }
        rollingPolicy.start();
        super.start();
    }

    /**
     * 滚动日志文件
     */
    private void rollover() {
        try {
            close();
        } catch (IOException e) {
            throw new RolloverFailure("关闭文件失败", e);
        }
        rollingPolicy.rollover(getActiveFile());
        openFile();
    }

    public RollingPolicy getRollingPolicy() {
        return rollingPolicy;
    }

    public void setRollingPolicy(RollingPolicy rollingPolicy) {
        this.rollingPolicy = rollingPolicy;
    }
}
